<template>
  <div>
    <el-upload
      action=""
      :show-file-list="false"
      :before-upload="
              (file) => handleBeforeUpload(file)
            "
      class="avatar-uploader"
      accept=".jpg,.jpeg,.png,.gif"
    >
      <img v-if="picUrl" :src="picUrl" class="avatar"/>
      <i v-else class="el-icon-plus avatar-uploader-icon"/>
    </el-upload>
    <image-cropper
      v-model="showCrop"
      :imgSrc="imgSrc"
      :cropWidth="cropWidth"
      :cropHeight="cropHeight"
      @uploadSuccess="uploadSuccess"
    ></image-cropper>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { uploadPath } from '@/api/business/storage'
import ImageCropper from "@/components/ImageCropper"

export default {
  name: "ShopUpLoad",
  components: {
    ImageCropper
  },
  props: {
    picUrl: {
      type: [String],
      default: () => {
      }
    },
    cropWidth: {
      type: [Number],
      default: () => 200
    },
    cropHeight: {
      type: [Number],
      default: () => 100
    }
  },
  data() {
    return {
      uploadPath,
      showCrop: false, // 展示裁切框
      imgSrc: ""
    }
  },
  computed: {
    headers() {
      return {
        "X-Dts-Merchant-Token": getToken(),
      };
    }
  },
  methods: {
    handleBeforeUpload(file) {
      this.imgSrc = URL.createObjectURL(file) // 创建图片地址用于显示和裁切
      this.showCrop = true // 打开裁切对话框
      return false // 不自动上传，由用户手动触发上传
    },
    uploadSuccess(url) {
      // 返回给父组件
      this.$emit('on-upload-success', {
        picUrl: url
      })
    }
  }
}
</script>

<style scoped>

</style>
